package com.lap.auth.domain.msg.service;

import java.util.Optional;
import com.lap.auth.domain.msg.MsgTemplate;
import com.lap.auth.domain.msg.repository.MsgTemplateRepository;
import com.lap.auth.domain.shared.errors.UserError;
import com.lap.framework.exception.BizException;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class MsgTemplateValidator {

  private final MsgTemplateRepository msgTemplateRepository;

  public MsgTemplate assertMsgTemplateExists(Integer id) {
    return msgTemplateRepository.findById(id)
        .orElseThrow(() -> BizException.newBiz(UserError.MSG_TEMPLATE_NOT_FOUND));
  }

  public void validateCodeUnique(MsgTemplate msgTemplate, boolean isUpdate) {
    Optional<MsgTemplate> optional = msgTemplateRepository.findByCode(msgTemplate.getCode());
    optional.ifPresent(p -> {
      if (!isUpdate || !p.getId().equals(msgTemplate.getId())) {
        BizException.interrupt(UserError.MSG_TEMPLATE_EXISTS);
      }
    });
  }
}
